package com.bdth.bdthmall.api.epoint.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.bdth.bdthmall.api.annotation.AuthToken;
import com.bdth.bdthmall.api.datas.CommonDatas;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2020/1/11.
 */
public class TokenInterceptor implements HandlerInterceptor {
    private static Logger log = LoggerFactory.getLogger(TokenInterceptor.class);
    //鉴权失败后返回的HTTP错误码，默认为401
    private int unauthorizedErrorCode = HttpServletResponse.SC_UNAUTHORIZED;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //验证token
        if (method.getAnnotation(AuthToken.class) != null || handlerMethod.getBeanType().getAnnotation(AuthToken.class) != null) {
            String data = request.getParameter("data");
            System.out.println(data);
            JSONObject json = JSONObject.parseObject(data);
            String token = json.getString("accessToken");
            log.info("获取到的token为: {} ", token);
            //此处主要设置你的redis的ip和端口号，我的redis是在本地

            String username = null;
            if (token != null && token.length() != 0) {
                //从redis中根据键token来获取绑定的username
                username = CommonDatas.epointToken.get(token);
                log.info("从内存中获取的用户名称为: {}", username);
            }
            //判断username不为空的时候
            if (username != null && !username.trim().equals("")) {
                String startBirthTime = CommonDatas.epointTokenTime.get(token);
                log.info("生成token的时间为: {}", startBirthTime);
                //
                Long time = System.currentTimeMillis() - Long.valueOf(startBirthTime);
                log.info("token存在时间为 : {} ms", time);
                //重新设置内存中的token过期时间
                if(time>CommonDatas.epoint_Token_Keep_Time){
                    CommonDatas.epointToken.remove(token);
                    CommonDatas.epointAppKey.remove(username);
                    CommonDatas.epointTokenTime.remove(token);
                    //删除内存中的token
                    return false;
                }else{
                    Long start = System.currentTimeMillis();
                    CommonDatas.epointTokenTime.put(token,start.toString());
                }
                return true;
            } else {
                JSONObject jsonObject = new JSONObject();
                PrintWriter out = null;
                try {
                    response.setStatus(unauthorizedErrorCode);
                    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                    jsonObject.put("isSuccess", false);
                    //鉴权失败后返回的错误信息，默认为401 unauthorized
                    jsonObject.put("returnMsg", HttpStatus.UNAUTHORIZED);
                    jsonObject.put("accessToken","");
                    out = response.getWriter();
                    out.println(jsonObject);
                    return false;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (null != out) {
                        out.flush();
                        out.close();
                    }
                }
            }
        }
        return true;
    }

}
